package com.million.educenter.controller;

import com.google.gson.Gson;
import com.million.commonutils.JwtUtils;
import com.million.educenter.entity.UcenterMember;
import com.million.educenter.service.UcenterMemberService;
import com.million.educenter.utils.ConstantPropertiesUtil;
import com.million.educenter.utils.HttpClientUtils;
import com.million.servicebase.exception.GuliException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.HashMap;

/**
 * @Author: studyboy
 * @Date: 2022/4/5  11:36
 * 生产微信登录二维码 并回显数据
 */

@CrossOrigin
@Controller
@RequestMapping("/api/ucenter/wx")
public class WxApiController {

    @Autowired
    private UcenterMemberService ucenterMemberService;


    //2 获取扫描人信息，添加数据
    @GetMapping("callback")
    public String callback (String code, String state) {

        // 1.扫描之后，执行本地callback方法，得到code 和state
        //向认证服务器发送请求换取access_token
        String baseAccessTokenUrl =
                "https://api.weixin.qq.com/sns/oauth2/access_token" +
                        "?appid=%s" +
                        "&secret=%s" +
                        "&code=%s" +
                        "&grant_type=authorization_code";
        String accessTokenUrl = String.format(baseAccessTokenUrl,
                ConstantPropertiesUtil.WX_OPEN_APP_ID,
                ConstantPropertiesUtil.WX_OPEN_APP_SECRET,
                code);
        String result = null;
        try {
            //2.请求这个拼接号的地址，得到返回两个值 access_token 和openid
            //使用httpClient 发送请求，得到返回结果
            result = HttpClientUtils.get(accessTokenUrl);
            //从result 字符串获取access_token 和openid
            //把accessToken 字符串转换成map集合，根据map 里面key获取对应值
            //使用json 转换工具 Gson
            Gson gson = new Gson();
            HashMap mapAccessToken = gson.fromJson(result, HashMap.class);
            String access_token = (String) mapAccessToken.get("access_token");
            String openid = (String) mapAccessToken.get("openid");

            //3.拿到得到的access_token和openid 再去请求微信提供固定的地址，获取到扫码人信息
            //访问微信的资源服务器，获取用户信息
            String baseUserInfoUrl = "https://api.weixin.qq.com/sns/userinfo" +
                    "?access_token=%s" +
                    "&openid=%s";
            String userInfoUrl = String.format(baseUserInfoUrl, access_token, openid);
            //发送请求
            String userInfo = HttpClientUtils.get(userInfoUrl);
            //获取返回userInfo字符串扫码人信息
            HashMap usrInfoMap = gson.fromJson(userInfo, HashMap.class);
            String nickname = (String) usrInfoMap.get("nickname"); //昵称
            String headImgUrl = (String) usrInfoMap.get("headimgurl"); //头像

            //4 添加到数据库中，进行注册
            //先判断数据库中是否有相同的openid
            UcenterMember member = ucenterMemberService.getMemberByOpenId(openid);
            //有数据说明是第二次登录，看看头像和昵称有没有变化
            if (member != null && (!nickname.equals(member.getNickname()) || !headImgUrl.equals(member.getAvatar()))) {
                member = new UcenterMember();
                member.setOpenid(openid);
                member.setNickname(nickname);
                member.setAvatar(headImgUrl);
                ucenterMemberService.save(member); //更新 头像和昵称
            }
            if (member == null) {  //不存在相同的openid 加入

                //3.拿到得到的access_token和openid 再去请求微信提供固定的地址，获取到扫码人信息
                //访问微信的资源服务器，获取用户信息
                baseUserInfoUrl = "https://api.weixin.qq.com/sns/userinfo" +
                        "?access_token=%s" +
                        "&openid=%s";
                userInfoUrl = String.format(baseUserInfoUrl, access_token, openid);
                //发送请求
                userInfo = HttpClientUtils.get(userInfoUrl);
                //获取返回userInfo字符串扫码人信息
                usrInfoMap = gson.fromJson(userInfo, HashMap.class);
                nickname = (String) usrInfoMap.get("nickname"); //昵称
                headImgUrl = (String) usrInfoMap.get("headimgurl"); //头像

                member = new UcenterMember();
                member.setOpenid(openid);
                member.setNickname(nickname);
                member.setAvatar(headImgUrl);
                ucenterMemberService.save(member);
            }
            //使用jwt生成token 字符串
            String jwtToken = JwtUtils.getJwtToken(member.getId(), member.getNickname());
            //最后：返回首页面 ，通过路径传递token字符串
            //因为端口号不同存在跨域问题，cookie不能跨域，所以这里使用url重写
            return "redirect:http://localhost:3000?token=" + jwtToken;
        } catch (Exception e) {
            throw new GuliException(20001, "登录失败");
        }
    }

    //1.生成微信二维码
    @GetMapping("login")
    public String genQrConnect () {

        // 微信开放平台授权baseUrl, %s相当于? 占位符
        String baseUrl = "https://open.weixin.qq.com/connect/qrconnect" +
                "?appid=%s" +
                "&redirect_uri=%s" +
                "&response_type=code" +
                "&scope=snsapi_login" +
                "&state=%s" +
                "#wechat_redirect";

        //需要对redirect_uri进行URLEncode编码
        String redirect_url = ConstantPropertiesUtil.WX_OPEN_REDIRECT_URL;
        try {
            redirect_url = URLEncoder.encode(redirect_url, "UTF-8");
        } catch (UnsupportedEncodingException e) {
            throw new GuliException(20001, "登录失败");
        }

        //设置%s 里面的值
        String url = String.format(baseUrl,
                ConstantPropertiesUtil.WX_OPEN_APP_ID,
                redirect_url,
                "shilu");

        //重定向到请求微信地址里面
        return "redirect:" + url;
    }
}
